package com.nintendo.service.impl;

import com.nintendo.config.MinIOConfig;
import com.nintendo.config.MinIOUtils;
import com.nintendo.service.FileService;
import com.nintendo.utils.JsonUtils;
import com.nintendo.utils.QrCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

@Service
public class FileServiceImpl implements FileService {
    @Resource
    private MinIOConfig minIOConfig;
    @Override
    public String generateQrCode(String userId, String wechatNum) {
        Map<String,String> map = new HashMap<>();
        map.put("wechatNum",wechatNum);
        map.put("userId",userId);
        String data = JsonUtils.objectToJson(map);
        String qrCodePath = QrCodeUtils.generateQRCode(data);
        if (StringUtils.isNotBlank(qrCodePath)) {
            String uuid = UUID.randomUUID().toString();
            String objectName = "wechatNumber" + "_" + userId + "_" + uuid + ".png";
            String imageQrCodeUrl = null;
            try {
                imageQrCodeUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(), objectName, qrCodePath, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return imageQrCodeUrl;
        }
        return null;
    }

    @Override
    public String uploadImage(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String objectName = UUID.randomUUID().toString().replace("-", "") + suffixName;
        try {
            String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(), objectName, file.getInputStream(), true);
            return imageUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<String> multUploadImage(MultipartFile[] files) {
        List<String> uploadImages = new ArrayList<>();
        for (MultipartFile file : files) {
            String filename = file.getOriginalFilename();
            String suffixName = filename.substring(filename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString().replace("-", "") + suffixName;
            try {
                String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(), objectName, file.getInputStream(), true);
                uploadImages.add(imageUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return uploadImages;
    }
}
